package com.jblog.controller.directive;

import static com.jblog.Constants.Encoding.UTF8;
import static com.jblog.Constants.Template.TPL_STYLE_LIST;
import static com.jblog.Constants.Template.TPL_SUFFIX;
import static com.jblog.common.web.freemarker.DirectiveUtils.OUT_LIST;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jblog.common.web.freemarker.DirectiveUtils;
import com.jblog.controller.directive.abs.AbstractArchiveDirective;
import com.jblog.core.model.blog.archive.PostCalendarArchive;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@SuppressWarnings({"unchecked", "rawtypes"})
public class ArchiveDirective extends AbstractArchiveDirective {
    
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        
        Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, wrap(params, env));

        env.include(TPL_STYLE_LIST + DirectiveUtils.getStyleList(params) + TPL_SUFFIX, UTF8, true);
        
        DirectiveUtils.removeParamsFromVariable(env, params, origMap);
    }
    
    protected Map<String, TemplateModel> wrap(Map<String, TemplateModel> params, 
            Environment env) throws TemplateException {
        
        Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
        
        if (super.isPostCalendar(params)) {
            paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap((List<PostCalendarArchive>)super.getData(params, env)));
        } 
        
        return paramWrap;
    }
}

